﻿using com.iot.core.boot;
using com.iot.core.exception;
using com.iot.core.infrastructure;
using com.iot.ht.Controllers.httask.data;
using System.Collections.Generic;

namespace com.iot.ht.Controllers.httask.service
{
    public abstract class HtAbstractTask
    {
        public HtTaskAppStateDto HtTaskAppStateDto { get; set; }
        public async  Task ExecuteAsync(CancellationToken stoppingToken)
        {
            try
            {                 
                if( (DateTime.Now- HtTaskAppStateDto.LstDt).TotalSeconds< HtTaskAppStateDto.HtTaskApp.Interval)
                {
                    return;
                }
                var r=await RunAsync(stoppingToken);
                if (r.Code == 0 || r.Code == 1)
                {
                    HtTaskAppStateDto.LstDt = DateTime.Now;
                    HtTaskAppStateDto.LstResult = r.Code == 0;
                    HtTaskAppStateDto.LstMsg =r.Msg;
                    var msg = r.Code == 0 ? "执行成功 " + r.Msg : "执行失败 "+ r.Msg;                     
                    Singleton<HtTaskService>.Instance.AddLog(HtTaskAppStateDto.HtTaskApp, msg);
                }
                else
                {
                   // HtTaskAppStateDto.LstDt = DateTime.Now;
                }
            }
            catch (Exception ex)
            {
                HtTaskAppStateDto.LstDt = DateTime.Now;
                HtTaskAppStateDto.LstResult = false;
                var msg = MyExceptionUtil.GetExMsg(ex);
                HtTaskAppStateDto.LstMsg= msg; 
                msg = "执行失败" + msg;
                Singleton<HtTaskService>.Instance.AddLog(HtTaskAppStateDto.HtTaskApp, msg);

            }
        }

        public abstract Task<MyApiResult> RunAsync(CancellationToken stoppingToken);
    }
}
